package zeus

import (
	"github.com/go-martini/martini"
	"reflect"
)

type Zeus struct {
	*martini.Martini
	martini.Router

	db interface{}
}

func Fighting() *Zeus {

	z := &Zeus{Martini: martini.New(), Router: martini.NewRouter()}
	z.Use(martini.Logger())
	z.Use(martini.Recovery())
	z.Use(martini.Static("public"))

	z.MapTo(z.Router, (*martini.Routes)(nil))
	z.Action(z.Router.Handle)

	return z
}

//控制器
func (this *Zeus) Controller(group string, classes ...IClass) *Zeus {

	this.Group(group, func(router martini.Router) {
		for _, clazz := range classes {
			clazz.Route(this) // 遍历所有IController的具体实现， 并注册Route  这才是关键 !!!

			//TODO: 采用反射注入到控制器中
			vClass := reflect.ValueOf(clazz).Elem()
			if vClass.NumField() > 0 {
				if this.db != nil {
					vClass.Field(0).Set(reflect.New(vClass.Field(0).Type().Elem()))
					vClass.Field(0).Elem().Set(reflect.ValueOf(this.db).Elem())
				}
			}
		}

	})

	return this
}

func (this *Zeus) Start() {
	this.Run()
}

//设置数据库链接对象
func (this *Zeus) DB(db interface{}) *Zeus {
	this.db = db
	return this
}
